package com.xiaoyu.client.ui.fragment.main;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.android.phone.mrpc.core.RpcException;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.seek.HelpRecyAdapter;
import com.xiaoyu.client.model.seek.SeekBean;
import com.xiaoyu.client.model.seek.SeekParam;
import com.xiaoyu.client.model.seek.SeekTypeBean;
import com.xiaoyu.client.model.seek.SeekTypeBean.SeekTypeParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.help.DiscoveryActivity;
import com.xiaoyu.client.ui.activity.help.SeekAddActivity;
import com.xiaoyu.client.ui.activity.help.HelpDetailActivity;
import com.xiaoyu.client.ui.activity.help.MyHelpActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.OnItemRecyClickListener;
import com.xiaoyu.commonlib.ui.widget.LabelsView;
import com.xiaoyu.commonlib.utils.AccessLocation;
import com.xiaoyu.commonlib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 求助模块
 * Created by jk on 2018/9/28.
 */
public class HelpFragment extends Fragment implements View.OnClickListener {
    public static final String SEEK_ID = "fragment_help_seek_id";
    private View mView;
    private TextView allBtn;//全部按钮
    private TextView locateBtn;//定位按钮
    private LinearLayout functionBar;//功能栏
    private RelativeLayout titleLayout;//顶部导航栏
    private ImageView addBtn;//发求助按钮
    private SeekFilterDialog filterDialog;
    private RecyclerView listContainer;//数据列表容器
    private SmartRefreshLayout mRefreshLayout;//刷新容器
    private List<SeekParam> mHelpList = new ArrayList<>();

    private List<SeekTypeParam> mTypeList = new ArrayList<>();//求助类别数据

    private HelpRecyAdapter mHelpAdapter;

    private int page = 1;//页数
    private int count = 0;//数据总条数

    private int status = -1;//0、未解决  1、已解决  -1、全部
    private String typeStr = "";//选择的类型id拼接字符串
    private boolean hasType = false;
    private LocationClient mLocationClient = null;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_help, container, false);
            initView();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mLocationClient.start();
        page = 1;
        mHelpList.clear();
        mHelpAdapter.updateList(mHelpList);
        getSeekInfo();
    }


    //初始化控件
    private void initView() {
        allBtn = mView.findViewById(R.id.fragment_help_title_txt);
        locateBtn = mView.findViewById(R.id.fragment_help_title_located_btn);
        functionBar = mView.findViewById(R.id.fragment_help_function_bar);
        titleLayout = mView.findViewById(R.id.fragment_help_title_layout);
        mRefreshLayout = mView.findViewById(R.id.fragment_help_refresh_layout);
        listContainer = mView.findViewById(R.id.fragment_help_list_container);
        addBtn = mView.findViewById(R.id.fragment_help_publish_btn);

        initRecy();

        //上拉下拉刷新设置
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });


        //初始化定位对象
        mLocationClient = new LocationClient(getActivity().getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("GCJ02");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);

        mRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mRefreshLayout.setNoMoreData(false);

        allBtn.setOnClickListener(this);
        addBtn.setOnClickListener(this);
        for (int i = 0; i < functionBar.getChildCount(); i++) {
            if (i != 0)
                functionBar.getChildAt(i).setOnClickListener(this);
        }


    }

    //初始化Recy列表
    private void initRecy() {
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.divider_recy_gray));
        listContainer.addItemDecoration(divider);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mHelpAdapter = new HelpRecyAdapter(getActivity(), mHelpList);
        listContainer.setAdapter(mHelpAdapter);
        listContainer.setLayoutManager(manager);

        mHelpAdapter.setOnItemRecyClickListener(onItemRecyClickListener);
    }


    /**
     * 定位监听
     */
    private BDAbstractLocationListener myListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            Log.i("xiaoyuu","经纬度  经度： "+bdLocation.getLongitude()+"   纬度：  "+bdLocation.getLatitude()
                    +"   街道： "+bdLocation.getStreet()+"   type = "+bdLocation.getLocType()
                    +"   省份 ： "+bdLocation.getProvince()+"  城市： "+bdLocation.getCity()+"  addstr : "+bdLocation.getAddrStr()
                    +"  描述："+bdLocation.getLocationDescribe());
            locateBtn.setText(bdLocation.getProvince());
            mLocationClient.stop();
        }
    };

    @Override
    public void onClick(View v) {
        if (v == functionBar.getChildAt(1)) {//发现
            startActivity(new Intent(getActivity(), DiscoveryActivity.class));
        } else if (v == functionBar.getChildAt(2)) {//我的求助
            startActivity(new Intent(getActivity(), MyHelpActivity.class));
        } else if (v == allBtn) {//全部
            if (filterDialog == null){
                filterDialog = new SeekFilterDialog(getActivity());
            }
            if (!filterDialog.isShowing()){
                filterDialog.show();
            }else {
                filterDialog.dismiss();
            }
        } else if (v == addBtn) {//发求助
            startActivity(new Intent(getActivity(), SeekAddActivity.class));
        }
    }


    /**
     * 求助列表item点击监听
     */
    private OnItemRecyClickListener onItemRecyClickListener = new OnItemRecyClickListener() {

        @Override
        public void onItemRecyClick(View view, int position) {
            Intent intent = new Intent(getActivity(), HelpDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(ClientConstants.FROM, ClientConstants.HELP_FRAGMENT);
            bundle.putString(SEEK_ID, mHelpList.get(position).getSeekid());
            intent.putExtras(bundle);
            startActivity(intent);
        }

    };

    //刷新监听
    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            page = 1;
            mHelpList.clear();
            mHelpAdapter.updateList(mHelpList);
            getSeekInfo();
            mRefreshLayout.finishRefresh();
        }
    };

    //加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < count) {
                page = page + 1;
                getSeekInfo();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                Toast.makeText(getActivity(), "已经没有更多数据！！！", Toast.LENGTH_LONG).show();
            }
        }
    };

    /**
     * 获取求助列表
     */
    private void getSeekInfo() {
        NetworkManager.getSeekList(page, status, typeStr,new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseSeekInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

    //解析求助列表接口数据成功

    private void parseSeekInfoSuc(String result) {
        if (page == 1) {
            mHelpList.clear();
            mHelpAdapter.updateList(mHelpList);
        }
        SeekBean seekBean = new Gson().fromJson(result, SeekBean.class);
        if (seekBean.getSeekData().getList() == null || seekBean.getSeekData().getList().size() == 0) {
            return;
        }

        mHelpList.addAll(seekBean.getSeekData().getList());
        count = Integer.parseInt(seekBean.getSeekData().getCount());
        mHelpAdapter.updateList(mHelpList);
    }


//    private Map<String,SeekTypeParam> mSelectList = new HashMap<>();//选择的类别列表数据
    private List<String> mSelectList = new ArrayList<>();//选择的类别列表数据

    class SeekFilterDialog extends Dialog implements View.OnClickListener{

        private RadioGroup statusGroup;
        private LabelsView labelsView;
        private TextView cancelBtn;
        private TextView confirmlBtn;
        private View blankView1;//空白区域1
        private View blankView2;//空白区域2

        public SeekFilterDialog(@NonNull Context context) {
            super(context, R.style.MyDialog);
            getTypeInfo();
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.popup_help_filter);//这行一定要写在前面
            statusGroup = findViewById(R.id.popup_help_filter_status_layout);
            labelsView = findViewById(R.id.popup_help_filter_type_list);
            cancelBtn = findViewById(R.id.popup_help_filter_cancel_btn);
            confirmlBtn = findViewById(R.id.popup_help_filter_confirm_btn);
            blankView1 = findViewById(R.id.blank_view1);
            blankView2 = findViewById(R.id.blank_view2);



            labelsView.setOnLabelSelectChangeListener(selectChangeListener);
            cancelBtn.setOnClickListener(this);
            confirmlBtn.setOnClickListener(this);
            blankView1.setOnClickListener(this);
            blankView2.setOnClickListener(this);
            statusGroup.setOnCheckedChangeListener(onCheckedChangeListener);


            setCancelable(true);//点击外部不可dismiss
            setCanceledOnTouchOutside(true);

            Window window = this.getWindow();
            window.setGravity(Gravity.TOP);
            window.setWindowAnimations(R.style.dialogTopAnim);//设置滑出动画
            window.setDimAmount(0f);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.MATCH_PARENT ;
            params.x = 0;
            params.y = titleLayout.getHeight();
            window.setAttributes(params);
        }

        @Override
        public void onClick(View v) {
            if (v == cancelBtn) {
                dismiss();
            } else if (v == confirmlBtn) {
                if (mSelectList.size() != 0){
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0;i<mSelectList.size();i++) {
                        builder.append(mSelectList.get(i));
                        builder.append(i == mSelectList.size() - 1 ? "":",");
                    }
                    typeStr = builder.toString();
                }
                page = 1;
                mHelpList.clear();
                mHelpAdapter.updateList(mHelpList);
                getSeekInfo();
                dismiss();
            }else if (v == blankView1 || v == blankView2){//空白区域
                dismiss();
            }
        }

        private LabelsView.OnLabelSelectChangeListener selectChangeListener = new LabelsView.OnLabelSelectChangeListener() {
            @Override
            public void onLabelSelectChange(View label, String labelText, boolean isSelect, int position) {
                if (isSelect){
                    mSelectList.add(mTypeList.get(position).getSeephelpid());
                }else {
                    if (mSelectList.contains(mTypeList.get(position).getSeephelpid())){
                        mSelectList.remove(mTypeList.get(position).getSeephelpid());
                    }
                }
            }
        };

        private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.popup_help_filter_status_all://全部
                        status = -1;
                        ToastUtil.showToast(getContext(),"点击全部 state = "+status);
                        break;
                    case R.id.popup_help_filter_status_solved://已解决
                        status = 1;
                        ToastUtil.showToast(getContext(),"点击已解决 state = "+status);
                        break;
                    case R.id.popup_help_filter_status_unsolved://未解决
                        status = 0;
                        ToastUtil.showToast(getContext(),"点击未解决 state = "+status);
                        break;
                }
            }
        };


        /**
         * 获取求助类别信息
         */
        private void getTypeInfo(){
            mTypeList.clear();
            NetworkManager.getSeekType(new CommonHttpResponser() {
                @Override
                public void onSuccess(String result) {
                    parseTypeInfoSuc(result);
                }

                @Override
                public void onFailed(String errorCode, String errorDiscription) {

                }
            });
        }

        private void parseTypeInfoSuc(String result) {
            ToastUtil.logResult("求助类别",result);
            SeekTypeBean bean = new Gson().fromJson(result,SeekTypeBean.class);
            mTypeList.addAll(bean.getType());
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0;i<mTypeList.size();i++){
                list.add(mTypeList.get(i).getSeephelpname());
            }
            labelsView.setLabels(list);
        }

    }



}











































